package com.collectplus.express.evaluate;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.collectplus.express.BaseActivityWithScroll;
import com.collectplus.express.R;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.model.OrderEvaluateBean;
import com.collectplus.express.model.OrderEvaluateResultBean;
import com.collectplus.express.order.EvaluateItemAdapter;
import com.collectplus.express.parcel.LargePicturePreviewActivity;
import com.collectplus.express.view.RatingBar;

import java.util.ArrayList;
import java.util.HashSet;

import droid.frame.utils.GlideUtil;
import droid.frame.utils.lang.Str;

/**
 * 服务评价
 *
 * @author HuXinDan<br>
 *         2016-11-8上午9:27:24
 */
public class EvaluateActivity extends BaseActivityWithScroll implements OnClickListener {

    private TextView mEvaluate;

    private Button mSubmitBtn; // 提交按钮
    private LinearLayout mGoodLayout;// 赞的标签
    private LinearLayout mBadLayout;// 踩得标签
    private EditText mRemark;// 填写的内容
    private OrderEvaluateResultBean items;

    private LinearLayout mServiceEmptyLayout, evaluateGoodTitle, evaluateBadTitle;// 初始状态
    private LinearLayout mCourierScore;//评分

    private ImageView mGoodImage;// 赞
    private ImageView mBadImage;// 踩
    private ImageView mCourierHeadPortrait;//火箭侠头像
    private TextView mCourierName;//火箭侠名字

    private RatingBar ratingBar;

    private String orderId;
    // private String parcelId;

    private EvaluateItemAdapter mGoodAdapter;// 好的标签
    private EvaluateItemAdapter mBadAdapter;// 差的标签
    private TextView scoreTv;//分数

    private HashSet<Integer> checkedSet = new HashSet<Integer>();
    // 是否已经选择赞 或者踩
    private boolean isSelected = false;
    private float marks;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        orderId = getIntent().getStringExtra("orderId");
        // parcelId = getIntent().getStringExtra("parcelId");
        super.onCreate(savedInstanceState);
        // orderId = "9109";// "9131";
        showLoadingDialog(null);
        AppHttp.getInstance().orderEvaluateGet(orderId);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.evaluate);
        super.findViewById();
        getAppTitle().setCommonTitle("服务评价");
        mGoodImage = (ImageView) findViewById(R.id.evaluate_good_checkedButton);
        mBadImage = (ImageView) findViewById(R.id.evaluate_bad_checkedButton);
        mEvaluate = (TextView) findViewById(R.id.evaluate_tips);
        mRemark = (EditText) findViewById(R.id.evaluate_edit);
        mServiceEmptyLayout = (LinearLayout) findViewById(R.id.evaluate_check_layout);
        mGoodLayout = (LinearLayout) findViewById(R.id.evaluate_good_layout);
        mBadLayout = (LinearLayout) findViewById(R.id.evaluate_bad_layout);

        mCourierScore = (LinearLayout) findViewById(R.id.courier_score_layout);
        //火箭侠头像
        mCourierHeadPortrait = (ImageView) findViewById(R.id.courier_head_portrait);
        mCourierHeadPortrait.setOnClickListener(this);
        //火箭侠名字
        mCourierName = (TextView) findViewById(R.id.courier_name_tv);

        evaluateGoodTitle = (LinearLayout) findViewById(R.id.evaluate_good_title_layout);
        evaluateBadTitle = (LinearLayout) findViewById(R.id.evaluate_bad_title_layout);
        scoreTv = (TextView) findViewById(R.id.score_tv);
        ratingBar = (RatingBar) findViewById(R.id.rb_five);
        ratingBar.setIntegerMark(true);
        ratingBar.setOnStarChangeListener(new RatingBar.OnStarChangeListener() {
            @Override
            public void onStarChange(float mark) {
                if (mark > 0) {
                    setButtonEnableStyle(mSubmitBtn, true);
                } else {
                    setButtonEnableStyle(mSubmitBtn, false);
                }
                marks = mark;
                scoreTv.setText(mark + "分");
            }
        });
        // 立即评价的按钮
        mSubmitBtn = (Button) findViewById(R.id.evaluate_submit);
        setButtonEnableStyle(mSubmitBtn, false);
        // set click event
        mGoodImage.setOnClickListener(this);
        mBadImage.setOnClickListener(this);
        this.mSubmitBtn.setOnClickListener(this);
        // 隐藏 除了 赞和踩之外的
        initView(View.GONE);

        getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // 向下移动500pix，然后再移动到原来的位置复原。
                // 参数“translationY”指明在Y坐标轴位移，即垂直位移。
                ObjectAnimator anim = ObjectAnimator.ofFloat(mServiceEmptyLayout, "translationY", 400f);
                anim.setDuration(0);
                // 正式开始启动执行动画
                anim.start();
            }
        }, 250);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            // 评价
            case MsgID.order_evaluate:
                cancelLoadingDialog();
                final AppResult<?> result1 = JSON.parser(msg.obj);
                if (result1.isSuccess()) {
                    showToast("评价成功");
                    Intent intent1 = new Intent();
                    setResult(Activity.RESULT_OK, intent1);
                    Intent intent = new Intent();
                    intent.setClass(getContext(), EvaluateCompleteActivity.class);
                    intent.putExtra("orderId", orderId);
                    startActivity(intent);
                    finish();
                } else {
                    showToast(result1.getMessage());
                }
                return true;
            // 获取评价项
            case MsgID.order_show_evaluate:
                cancelLoadingDialog();
                final AppResult<OrderEvaluateResultBean> result = JSON.parser(msg.obj, OrderEvaluateResultBean.class);
                if (result.isSuccess()) {
                    getContext().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            items = result.getResult();

                            // 差
                            if (items.getBad() != null && items.getBad().size() > 0) {
                                if (items.getBad().size() > 6) {
                                    ArrayList<OrderEvaluateBean> list = new ArrayList<>();
                                    list.addAll(items.getBad().subList(0, 6));
                                    mBadAdapter = new EvaluateItemAdapter(list, getContext());
                                } else {
                                    mBadAdapter = new EvaluateItemAdapter(items.getBad(), getContext());
                                }
                            } else {
                                mBadAdapter = new EvaluateItemAdapter(items.getBad(), getContext());
                            }
                            mBadAdapter = new EvaluateItemAdapter(items.getBad(), getContext());
                            mBadAdapter.setupLayout(mBadLayout);
                            // 好
                            if (items.getGood() != null && items.getGood().size() > 0) {
                                if (items.getGood().size() > 6) {
                                    ArrayList<OrderEvaluateBean> list = new ArrayList<>();
                                    list.addAll(items.getGood().subList(0, 6));
                                    mGoodAdapter = new EvaluateItemAdapter(list, getContext());
                                } else {
                                    mGoodAdapter = new EvaluateItemAdapter(items.getGood(), getContext());
                                }
                            } else {
                                mGoodAdapter = new EvaluateItemAdapter(items.getGood(), getContext());
                            }
                            mGoodAdapter.setupLayout(mGoodLayout);
                            //
                            if (isSelected) {
                                showGoodOrBad(isSelectedGood());
                            }
                        }
                    });
                } else {
                    showToast(result.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.evaluate_good_checkedButton:// 赞
                ObjectAnimator anim;
                float translationY = mServiceEmptyLayout.getTranslationY();
                if (translationY > 0) {
                    anim = ObjectAnimator.ofFloat(mServiceEmptyLayout, "translationY", 0);
                    anim.setDuration(250);
                    // 正式开始启动执行动画
                    anim.start();
                    anim.addListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            showGoodOrBad(true);
                        }
                    });
                } else {
                    showGoodOrBad(true);
                }
                break;
            case R.id.evaluate_bad_checkedButton:// 踩
                translationY = mServiceEmptyLayout.getTranslationY();
                if (translationY > 0) {
                    anim = ObjectAnimator.ofFloat(mServiceEmptyLayout, "translationY", 0);
                    anim.setDuration(250);
                    // 正式开始启动执行动画
                    anim.start();
                    anim.addListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            showGoodOrBad(false);
                        }
                    });
                } else {
                    showGoodOrBad(false);
                }
                break;
            // 确定按钮
            case R.id.evaluate_submit:
                String serviceRemark = mRemark.getText().toString();
                if ((items.getVisit() && marks > 0) || !items.getVisit()) {
                    showLoadingDialog(null);
                    if (isSelectedGood()) {
                        AppHttp.getInstance().orderEvaluate(orderId, marks, checkedSet, serviceRemark);
                    } else {
                        AppHttp.getInstance().orderEvaluate(orderId, marks, checkedSet, serviceRemark);
                    }
                }
                break;
            case R.id.courier_head_portrait:
                if (!Str.isEmpty(items.getImagePath())) {
                    Intent largeIntent = new Intent(this, LargePicturePreviewActivity.class);
                    largeIntent.putExtra("picUrl", items.getImagePath());
                    startActivity(largeIntent);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 是否选择的 "赞"
     *
     * @return false 表示踩
     */
    public boolean isSelectedGood() {
        return mEvaluate.getText().toString().equals(getResources().getString(R.string.order_praise));
    }

    private void initView(int visible) {
        evaluateGoodTitle.setVisibility(visible);
        evaluateBadTitle.setVisibility(visible);
        mGoodLayout.setVisibility(visible);
        mBadLayout.setVisibility(visible);
        mRemark.setVisibility(visible);
        mSubmitBtn.setVisibility(visible);
        mCourierScore.setVisibility(visible);
    }

    private void showGoodOrBad(boolean good) {
        if (mGoodAdapter == null || mGoodAdapter.isEmpty()) {
            return;
        }
        if (null != items && items.getVisit() && marks > 0) {
            setButtonEnableStyle(mSubmitBtn, true);
        } else {
            if (items == null || !items.getVisit()) {
                setButtonEnableStyle(mSubmitBtn, true);
            } else {
                setButtonEnableStyle(mSubmitBtn, false);
            }
        }
        isSelected = true;
        //        initView(View.VISIBLE);
        if (null != items && items.getVisit()) {
            mCourierScore.setVisibility(View.VISIBLE);
            GlideUtil.loadImage(getContext(), items.getImagePath(), R.drawable.visit_place_holder_icon, mCourierHeadPortrait);
            mCourierName.setText(items.getNickName());
        } else {
            mCourierScore.setVisibility(View.GONE);
        }

        mRemark.setVisibility(View.VISIBLE);
        mSubmitBtn.setVisibility(View.VISIBLE);
        if (good) {
            // 动画结束后
            mGoodImage.setImageResource(R.drawable.evaluate_good_2);
            mBadImage.setImageResource(R.drawable.evaluate_bad);
            mEvaluate.setText(getResources().getString(R.string.order_praise));
            mEvaluate.setTextColor(getResources().getColor(R.color.app_font_1));
            evaluateGoodTitle.setVisibility(View.VISIBLE);
            mGoodLayout.setVisibility(View.VISIBLE);
            evaluateBadTitle.setVisibility(View.GONE);
            mBadLayout.setVisibility(View.GONE);

        } else {
            mGoodImage.setImageResource(R.drawable.evaluate_good);
            mBadImage.setImageResource(R.drawable.evaluate_bad_2);
            mEvaluate.setText(getResources().getString(R.string.order_stamp));
            mEvaluate.setTextColor(getResources().getColor(R.color.app_font_1));
            evaluateBadTitle.setVisibility(View.VISIBLE);
            mBadLayout.setVisibility(View.VISIBLE);
            evaluateGoodTitle.setVisibility(View.GONE);
            mGoodLayout.setVisibility(View.GONE);

        }
    }

    /**
     * 更新选中的items
     */
    public void updateCheckedItems() {
        HashSet<Integer> checkedGoodSet = mGoodAdapter.getCheckedSet();
        HashSet<Integer> checkedBadSet = mBadAdapter.getCheckedSet();
        checkedSet.addAll(checkedGoodSet);
        checkedSet.addAll(checkedBadSet);
        // if (checkedGoodSet.size() > 0 || checkedBadSet.size() > 0) {
        // setButtonEnableStyle(mSubmitBtn, true);
        // } else {
        // setButtonEnableStyle(mSubmitBtn, false);
        // }
    }
}
